package com.example.api.service.impl;

import com.example.api.dao.CommodityDao;
import com.example.api.dao.PurchaseDao;
import com.example.api.model.entity.Commodity;
import com.example.api.model.entity.Purchase;
import com.example.api.model.vo.PurchaseInVo;
import com.example.api.service.PurchaseService;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PurchaseServiceImpl implements PurchaseService {

    @Resource
    private PurchaseDao purchaseDao;

    @Resource
    private CommodityDao commodityDao;

    @Override
    public List<PurchaseInVo> findAll() {
        List<Purchase> purchases = purchaseDao.findAll();
        if (purchases.isEmpty()) {
            return Lists.newArrayList();
        }
        List<Integer> cids = purchases
                .stream()
                .map(Purchase::getCid)
                .collect(Collectors.toList())
                .stream()
                .distinct()
                .collect(Collectors.toList());
        List<PurchaseInVo> list = Lists.newArrayList();
        for (Integer id : cids) {
            PurchaseInVo purchaseInVo = new PurchaseInVo();
            purchaseInVo.setCid(id);
            Commodity commodity = commodityDao.selectByPrimaryKey(id);
            purchaseInVo.setName(commodity.getName());
            int result = purchases.stream().filter(purchase -> purchase.getCid().equals(id)).mapToInt(Purchase::getCount).sum();
            purchaseInVo.setCount(result);
            list.add(purchaseInVo);
        }
        return list;
    }

}